package kim.sesame.util.pdf.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.apachecommons.CommonsLog;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

/**
 * pdf generate 和 splice
 * <!--https://www.cnblogs.com/wangpeng00700/p/8418594.html-->
 */
@CommonsLog
public class PdfUtils {

    public static final String MAP_KEY_DATEMAP = "datemap";// 数据的key
    public static final String MAP_KEY_IMGMAP = "imgmap";//图片的key
    public static final String MAP_KEY_TABLE = "tablemap";//表格的key


    private static final String FONT_PATH = "kim/sesame/util/pdf/font/simsun.ttc,1";// 默认字体文件,宋体
    private static final Integer FONT_SIZE = 3;// 默认字体大小

    /**
     * 利用模板生成pdf
     *
     * @param o            参数
     * @param templatePath 模板路径
     * @param newPDFPath   生成的路径
     */
    public static void tempGenerate(Map<String, Object> o, String templatePath, String newPDFPath) {
        tempGenerate(o, templatePath, newPDFPath, FONT_PATH, FONT_SIZE);
    }

    public static void tempGenerate(Map<String, Object> o, String templatePath, String newPDFPath, String fontPath) {
        tempGenerate(o, templatePath, newPDFPath, fontPath, FONT_SIZE);
    }

    public static void tempGenerate(Map<String, Object> o, String templatePath, String newPDFPath, String fontPath, Integer fontSize) {

        if (fontPath == null || fontPath.equals("")) {
            fontPath = FONT_PATH;
        }
        if (fontSize == null) {
            fontSize = FONT_SIZE;
        }
        PdfReader reader = null;
        FileOutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        try {
            BaseFont bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font FontChinese = new Font(bf, fontSize, Font.NORMAL);
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            //文字类的内容处理
            Map<String, String> datemap = (Map<String, String>) o.get(MAP_KEY_DATEMAP);
            form.addSubstitutionFont(bf);
            for (String key : datemap.keySet()) {
                String value = datemap.get(key);
                form.setField(key, value);
            }
            //图片类的内容处理
            Map<String, String> imgmap = (Map<String, String>) o.get(MAP_KEY_IMGMAP);
            for (String key : imgmap.keySet()) {
                String value = imgmap.get(key);
                String imgpath = value;
                int pageNo = form.getFieldPositions(key).get(0).page;
                Rectangle signRect = form.getFieldPositions(key).get(0).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();
                //根据路径读取图片
                Image image = Image.getInstance(imgpath);
                //获取图片页面
                PdfContentByte under = stamper.getOverContent(pageNo);
                //图片大小自适应
                image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                //添加图片
                image.setAbsolutePosition(x, y);
                under.addImage(image);
            }
            // 表格
            Map<String, List<List<String>>> listMap = (Map<String, List<List<String>>>) o.get(MAP_KEY_TABLE);
            for (String key : listMap.keySet()) {
                List<List<String>> lists = listMap.get(key);
                int pageNo = form.getFieldPositions(key).get(0).page;
                PdfContentByte pcb = stamper.getOverContent(pageNo);
                Rectangle signRect = form.getFieldPositions(key).get(0).position;
                //表格位置
                int column = lists.get(0).size();
                int row = lists.size();
                PdfPTable table = new PdfPTable(column);
                float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
                int size = lists.get(0).size();
                float width[] = new float[size];
                for (int i = 0; i < size; i++) {
                    if (i == 0) {
                        width[i] = 60f;
                    } else {
                        width[i] = (tatalWidth - 60) / (size - 1);
                    }
                }
                table.setTotalWidth(width);
                table.setLockedWidth(true);
                table.setKeepTogether(true);
                table.setSplitLate(false);
                table.setSplitRows(true);
                Font FontProve = new Font(bf, 5, 0);// 可以修改
                //表格数据填写
                for (int i = 0; i < row; i++) {
                    List<String> list = lists.get(i);
                    for (int j = 0; j < column; j++) {
                        Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
                        PdfPCell cell = new PdfPCell(paragraph);
                        cell.setBorderWidth((float) 0.5); // 可以修改
                        cell.setVerticalAlignment(Element.ALIGN_CENTER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setLeading(0, (float) 1.4);
                        table.addCell(cell);
                    }
                }
                table.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
            }

            stamper.setFormFlattening(true);// 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
            stamper.close();
            Document doc = new Document();
            Font font = new Font(bf, 32);
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            int n = reader.getNumberOfPages();// 获得总页码
            for (int j = 1; j <= n; j++) {
                PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), j);
                copy.addPage(importPage);
            }
            doc.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (out != null) {
                    out.close();
                }
                if (bos != null) {
                    bos.close();
                }
                if (stamper != null) {
                    stamper.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("pdf文件生成成功 : " + newPDFPath);
    }

    /**
     * pdf 拼接
     *
     * @param fileList 待拼接的文件集合
     * @param savepath 拼接之后新文件的位置
     */
    public static void splice(List<String> fileList, String savepath) {
        Document document = null;
        PdfCopy copy = null;
        PdfReader pdfReader = null;
        try {
            pdfReader = new PdfReader(fileList.get(0));
            document = new Document(pdfReader.getPageSize(1));

            copy = new PdfCopy(document, new FileOutputStream(savepath));
            document.open();
            for (int i = 0; i < fileList.size(); i++) {
                PdfReader reader = new PdfReader(fileList.get(i));
                int n = reader.getNumberOfPages();// 获得总页码
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);// 从当前Pdf,获取第j页
                    copy.addPage(page);
                }
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (copy != null) {
                copy.close();
            }
            if (document != null) {
                document.close();
            }
            if (pdfReader != null) {
                pdfReader.close();
            }
        }
    }


}